package org.yunshang.common.excel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class EasyExceUrlListConverter implements Converter<List<URL>> {


    @Override
    public Class<?> supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        /**
         *这里记得枚举类型为IMAGE
         */
        return CellDataTypeEnum.RICH_TEXT_STRING;
    }

    @Override
    public List<URL> convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(List<URL> value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {

        List<WriteCellData> data = new ArrayList<>();
        for (URL url : value) {
            InputStream inputStream = null;
            try {
                URLConnection urlConnection = url.openConnection();
                inputStream = urlConnection.getInputStream();
                byte[] bytes = IoUtils.toByteArray(inputStream);
                data.add(new WriteCellData<>(bytes));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        }
        WriteCellData writeCellData = new WriteCellData<>();
        writeCellData.setData(data);
        writeCellData.setType(CellDataTypeEnum.RICH_TEXT_STRING);
        return writeCellData;
    }


}
